package com.physics.mps.common.config.auth;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.physics.mps.common.config.constant.JWTConstants;
import com.physics.mps.common.config.constant.TokenConstants;
import com.physics.mps.common.exception.BusinessException;
import com.physics.mps.common.util.LoginUtil;
import com.physics.mps.entity.enums.CodeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author mcsoft
 * @date 2023/8/28 14:51
 */
@Log4j2
@RequiredArgsConstructor
@Component
public class CustomInterceptor extends LoginUtil implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        // 请求头 token
        String token = request.getHeader(TokenConstants.AUTHENTICATION);
        if (ObjectUtil.isEmpty(token)) {
            log.error("URL:{}", request.getRequestURL());
            throw new BusinessException(CodeEnum.LOGIN_TOKEN_NOT_EMPTY);
        }
        try {
            if (!JWTUtil.verify(token, TokenConstants.SECRET.getBytes())) {
                throw new BusinessException(CodeEnum.LOGIN_TOKEN_ERROR);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(CodeEnum.LOGIN_TOKEN_ERROR);
        }
        JWT jwt = JWTUtil.parseToken(token);
        String tokenKey = (String) jwt.getPayload(JWTConstants.KEY);
        log.info("set token Thread: {}, token : {}", Thread.currentThread().getName(), tokenKey);
        LoginUtil.TOKEN.set(token);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("remove token Thread: {}", Thread.currentThread().getName());
        // 移除
        remove();

        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
